package com.tianfeng.fenghuotoutiao.ui.fragment.picture;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.tianfeng.fenghuotoutiao.R;
import com.tianfeng.fenghuotoutiao.globle.ConstantUrl;
import com.tianfeng.fenghuotoutiao.net.api.user.ApiInviteFriendDesc;
import com.tianfeng.fenghuotoutiao.net.bean.ResInviteFriendDesc;
import com.tianfeng.fenghuotoutiao.net.bean.news.HomeTabBean;
import com.tianfeng.fenghuotoutiao.presenter.LoginPresenter;
import com.tianfeng.fenghuotoutiao.presenter.NewPictureFragmentPresenter;
import com.tianfeng.fenghuotoutiao.ui.activity.WebHelperActivity;
import com.tianfeng.fenghuotoutiao.ui.activity.base.BaseActivity;
import com.tianfeng.fenghuotoutiao.ui.adapter.NewAdapter;
import com.tianfeng.fenghuotoutiao.ui.adapter.PictureViewPagerAdapter;
import com.tianfeng.fenghuotoutiao.ui.base.BaseRecAdapter;
import com.tianfeng.fenghuotoutiao.ui.base.BaseRecViewHolder;
import com.tianfeng.fenghuotoutiao.ui.base.MyVideoPlayer;
import com.tianfeng.fenghuotoutiao.ui.dialog.invite.InviteFriendShareDialogFour;
import com.tianfeng.fenghuotoutiao.ui.fragment.base.BaseFragment;

import com.tianfeng.fenghuotoutiao.ui.view.NewsRefreshBanner;
import com.tianfeng.fenghuotoutiao.ui.view.TabMenuView;
import com.tianfeng.fenghuotoutiao.ui.view.VeticalDrawerLayout;
import com.tianfeng.fenghuotoutiao.ui.view.indicator.HomeTabIndicatorAdapter;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PictureFragment extends BaseFragment {

    @BindView(R.id.rv_page2)
    RecyclerView rvPage2;

    private List<String> urlList;
    private ListVideoAdapter videoAdapter;
    private PagerSnapHelper snapHelper;
    private LinearLayoutManager layoutManager;
   List<VideoModel.DataBean> videoModelList=new ArrayList<>();
    private PictureViewPagerAdapter mHomeViewPagerAdapter;

    private HomeTabIndicatorAdapter mHomeTabIndicatorAdapter;
    private NewPictureFragmentPresenter mPresenter;
    private LoginPresenter mLoginPresenter;
    private boolean tabSpecs;


    @Override
    protected void initView() {
        super.initView();
        mPresenter = new NewPictureFragmentPresenter(((BaseActivity) getActivity()));
        requestNetFromTabVideo();



    }






    @Override
    public void onResume() {
        super.onResume();
    }



    @Override
    protected View getContentView() {
        return inflatLayout(R.layout.fragment_new_picture);
    }







    @Override
    protected void initData() {
        super.initData();

    }






    /**
     * 请求小视频地址
     */
    public void requestNetFromTabVideo(){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url(String.format("http://tianze1688.com/api/index.php/news/user/getVideourl?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7"))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) return;
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String data=jsonObject.optString("data");
                    Gson gso=new Gson();
                   List<VideoModel.DataBean> videoModelList1=gso.fromJson(data,new TypeToken<List<VideoModel.DataBean>>(){}.getType());
                    videoModelList1.addAll(videoModelList);
                     getActivity().runOnUiThread(new Runnable() {
                         @Override
                         public void run() {
                             snapHelper = new PagerSnapHelper();
                             snapHelper.attachToRecyclerView(rvPage2);

                             Log.e("tag1111",videoModelList.size()+"");
                             videoAdapter = new ListVideoAdapter(videoModelList1);
                             layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                             rvPage2.setLayoutManager(layoutManager);
                             rvPage2.setAdapter(videoAdapter);
                             addListener();
                         }
                     });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



    private void addListener() {

        rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {


            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        View view = snapHelper.findSnapView(layoutManager);
                        JZVideoPlayer.releaseAllVideos();
                        RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
                        if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
                            ((VideoViewHolder) viewHolder).mp_video.startVideo();
                        }

                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        break;
                }

            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        JZVideoPlayer.goOnPlayOnPause();
    }
    private InviteFriendShareDialogFour mShareDialog;

    class ListVideoAdapter extends BaseRecAdapter<VideoModel.DataBean, VideoViewHolder> {


        public ListVideoAdapter(List<VideoModel.DataBean> list) {
            super(list);
        }

        @Override
        public void onHolder(VideoViewHolder holder, VideoModel.DataBean bean, int position) {
            ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;

            holder.mp_video.setUp(bean.getVideourl(), JZVideoPlayerStandard.CURRENT_STATE_NORMAL);
            if (position == 0) {
                holder.mp_video.startVideo();
            }

            int num = (int) ((Math.random() * 9 + 1) * 500);
            int num1 = (int) ((Math.random() * 9 + 1) * 500);
            holder.tv_zan_num.setText(String.valueOf(bean.getVideo_zan()>100?bean.getVideo_zan():num));
            holder.tv_zhuanfa_num.setText(String.valueOf(bean.getVideo_zhuanfa()>100?bean.getVideo_zhuanfa():num1));

            Glide.with(context).load(bean.getVideourl()).into(holder.mp_video.thumbImageView);
            holder.tv_title.setText(bean.getVideoname());
            holder.tv_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            holder.ll_zhuanfa.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String uid="";
                    if (getUserBean() != null) {
                        uid=getUserBean().getUserid();
                    }

                    //这里我们要做的一个操作就是
                    mShareDialog = new InviteFriendShareDialogFour(getBaseActivity(), null,uid);
                    mShareDialog.show();
                }
            });
            holder.likeBtn.setOnLikeListener(new OnLikeListener() {
                @Override
                public void liked(LikeButton likeButton) {
                    int i=Integer.valueOf(holder.tv_zan_num.getText().toString()).intValue();
                    holder.tv_zan_num.setText((i+1)+"");
                    add(bean.getId()+"");
                }

                @Override
                public void unLiked(LikeButton likeButton) {
                    int i1=Integer.valueOf(holder.tv_zan_num.getText().toString()).intValue();
                    holder.tv_zan_num.setText((i1-1)+"");
//                    sub(bean.getId()+"");
                }
            });
        }



        @Override
        public VideoViewHolder onCreateHolder() {
            return new VideoViewHolder(getViewByRes(R.layout.item_page2));

        }


    }

    public class VideoViewHolder extends BaseRecViewHolder {
        public View rootView;
        public MyVideoPlayer mp_video;
        public TextView tv_title;
        public TextView tv_zhuanfa_num;
        public TextView tv_zan_num;
        public LinearLayout ll_zhuanfa;
        public LikeButton likeBtn;


        public VideoViewHolder(View rootView) {
            super(rootView);
            this.rootView = rootView;
            this.mp_video = rootView.findViewById(R.id.mp_video);
            this.tv_title = rootView.findViewById(R.id.tv_title);
            this.ll_zhuanfa = rootView.findViewById(R.id.ll_zhuanfa);
            this.tv_zhuanfa_num = rootView.findViewById(R.id.tv_zhuanfa_num);
            this.tv_zan_num = rootView.findViewById(R.id.tv_zan_num);
            this.likeBtn = rootView.findViewById(R.id.likeBtn);
        }

    }

/**
 * ++赞
 */
public void add(String str){
    OkHttpClient okHttpClient=new OkHttpClient();
    final Request request = new Request.Builder()
            .url(String.format("http://tianze1688.com/api/index.php/news/user/getDianZanl?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7"+"&video_id="+str))
            .get()//默认就是GET请求，可以不写
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
//        http://tianze1688.com/api/index.php/news/user/getVideourl?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7
        public void onResponse(Call call, Response response) throws IOException {

        }
    });
}

    /**
     * --赞
     */
    public void sub(String str){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url(String.format("http://tianze1688.com/api/index.php/news/user/getDianZana?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7"+"&video_id="+str))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

}
